package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.BusinessEnum;

import com.powernode.domain.IndexImg;
import com.powernode.domain.Prod;

import com.powernode.ex.headler.BusinessException;
import com.powernode.feign.StoreProdFeign;
import com.powernode.mapper.IndexImgMapper;
import com.powernode.model.Result;
import com.powernode.service.IndexImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService{

    @Autowired
    private IndexImgMapper indexImgMapper;

    @Autowired
    private StoreProdFeign storeProdFeign;


    @Override
    public boolean saveIndexImg(IndexImg indexImg) {
        indexImg.setShopId(1L);
        indexImg.setCreateTime(new Date());
        // 获取关联类型
        Integer type = indexImg.getType();
        if(type == -1) {
//            说明轮播图未关联商品
            indexImg.setProdId(null);
        }
        return indexImgMapper.insert(indexImg) > 0;
    }

    @Override
    public IndexImg queryIndexImgInfoById(Long imgId) {
        IndexImg indexImg = indexImgMapper.selectById(imgId);
        if(indexImg.getType() == 0) {
//            关联商品 获取商品信息 远程调用
            Result<List<Prod>> result = storeProdFeign.getProdListByIds(Arrays.asList(indexImg.getProdId()));
//            判断是否正确
            if(BusinessEnum.OPERATION_FAIL.getCode().equals(result.getCode())) {
//                操作失败
                throw new BusinessException(result.getMsg());
            }
//            获取数据
            List<Prod> data = result.getData();
//            判断集合是否有值
            if(CollectionUtil.isNotEmpty(data) || data.size() != 0) {
                Prod prod = data.get(0);
                indexImg.setProdName(prod.getProdName());
                indexImg.setPic(prod.getPic());
            }
        }
        return indexImg;
    }

    @Override
    public boolean modifyIndexImg(IndexImg indexImg) {
        return indexImgMapper.updateById(indexImg) > 0;
    }

    @Override
    public Boolean removeIndexImgByIds(List<Long> imgIds) {
        return indexImgMapper.deleteBatchIds(imgIds) == imgIds.size();
    }
}
